using UnityEngine;
using System.Collections;
using System.Collections.Generic;

public class HideTargetsOnClick : MonoBehaviour
{
	public bool toggle = false;
	public bool m_IsHidden = false;
	public bool m_RestoreOnAnyClick = false;
	public bool m_ShowOnHover = false;
	
	public List<GameObject> TargetsToHide = new List<GameObject>();
	public List<GameObject> TargetsToShow = new List<GameObject>();
	
	private Dictionary<GameObject, bool> activenessMap = new Dictionary<GameObject, bool>();
	private bool m_wasHidden = false;
	
	void OnMouseDown()
	{
		if (toggle) m_IsHidden = !m_IsHidden;
		else m_IsHidden = true;
		
		List<GameObject> hideThese = (m_IsHidden) ? TargetsToHide : TargetsToShow;
		List<GameObject> showThese = (m_IsHidden) ? TargetsToShow : TargetsToHide;
		foreach( GameObject g in hideThese ) { StoreActiveness( g ); if ( g != null ) g.SetActive( false ); else Debug.LogWarning( "HideTargetsOnClick.OnClick() hideThese contains a null reference." ); }
		foreach( GameObject g in showThese ) { RestoreActiveness( g ); }
		m_wasHidden = m_IsHidden;
	}
	
	void OnMouseEnter()
	{
		if ( m_ShowOnHover ) m_IsHidden = false;
	}
	
	void OnMouseExit()
	{
		if ( m_ShowOnHover ) m_IsHidden = true;
	}
	
	void Update()
	{
		if ( (m_IsHidden != m_wasHidden) )
		{
			m_IsHidden = !m_IsHidden;
			OnMouseDown();
		}
		
		if (m_RestoreOnAnyClick && Input.GetMouseButtonDown( 0 ) && m_IsHidden )
		{
			//m_IsHidden = !m_IsHidden;
			bool tmp = toggle;
			toggle = true;
			OnMouseDown();
			toggle = tmp;
		}
	}
	
	void StoreActiveness( GameObject g )
	{
		//Debug.Log( "StoreActive: " + g.name);
		if ( g == null ) { Debug.LogWarning("HideTargetsOnClick.StoreActiveness( null )" ); return; }
		activenessMap[ g ] = g.activeInHierarchy;
		foreach( Transform t in g.transform )
		{
			StoreActiveness( t.gameObject );
		}
	}
	
	void RestoreActiveness( GameObject g )	
	{
		//Debug.Log( "RestoreActive: " + g.name);
		if ( g == null ) { Debug.LogWarning( "HideTargetsOnClick.RestoreActiveness( null )" ); return; }
		bool hidden;
		if ( activenessMap.TryGetValue( g, out hidden ) )
			 g.SetActive( hidden );
		else 
		{
			g.SetActive( true );
//			Debug.Log( "HideTargetsOnClick::RestoreActiveness() No entry for "+ g.name +"\n"  ); 
		}
		
		foreach( Transform t in g.transform )
		{
			RestoreActiveness( t.gameObject );
		}
	}
}
